﻿using CodeCarvings.Piczard;
using CodeCarvings.Piczard.Filters.Watermarks;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using ZSZ.Common;
using ZSZ.CommonMVC;
using ZSZ.DTO;
using ZSZ.IService;
using ZSZ.Model;
using ZSZ.Website.Areas.WebAdmin.Common;
using ZSZ.Website.Areas.WebAdmin.Filters;
using ZSZ.Website.Areas.WebAdmin.Models;

namespace ZSZ.Website.Areas.WebAdmin.Controllers
{
    public class HouseController : Controller
    {
        // GET: WebAdmin/House

        public IAdminUserService userSerivce { get; set; }

        public IHouseService houseService { get; set; }
        public IHousePicService housePicService { get; set; }

        public ICityService cityService { get; set; }
        public IRegionService regionService { get; set; }
        public ICommunityService communityService { get; set; }
        public IIdNameService idNameService { get; set; }
        public IAttachmentService attachmentService { get; set; }

        #region 列表
        [AdminAuthorize(IsCheck = true)]
        public ActionResult List(long typeId, int pageIndex = 1)
        {
            //因为AuthorizFilter做了是否登录的检查，因此这里不会取不到id
            long userId = (long)AdminHelper.GetUserId(HttpContext);
            long? cityId = userSerivce.GetById(userId).CityId;
            if (cityId == null)
            {
                //如果“总部不能***”的操作很多，也可以定义成一个AuthorizeFilter
                //最好用FilterAttribute的方式标注，这样对其他的不涉及这个问题的地方效率高
                //立即实现
                return View("Error", (object)"总部不能进行房源管理");
            }
            ViewBag.CityId = cityId;

            //房屋类别
            var type = idNameService.GetDTOById(typeId);
            ViewBag.Type = type;



            long total;
            int pageSize = 10, maxPagerCount = 10;
            var houses = houseService.GetPagedData(cityId.Value, typeId, out total, pageIndex, pageSize);
            ViewBag.totalCount = total;
            ViewBag.pageIndex = pageIndex;
            ViewBag.pageSize = pageSize;
            ViewBag.maxPagerCount = maxPagerCount;
            return View(houses);
        }
        #endregion

        #region 新增
        [HttpGet]
        [AdminAuthorize(IsCheck = true)]
        public ActionResult Add()
        {
            long? userId = AdminHelper.GetUserId(HttpContext);
            long? cityId = userSerivce.GetById(userId.Value).CityId;
            if (cityId == null)
            {
                return View("Error", (object)"总部不能进行房源管理");
            }
            var regions = regionService.GetByCityId(cityId.Value);
            var roomTypes = idNameService.GetAll("户型");
            var statuses = idNameService.GetAll("房屋状态");
            var decorateStatuses = idNameService.GetAll("装修状态");
            var attachments = attachmentService.GetAttachments();
            var types = idNameService.GetAll("房屋类别");

            HouseAddGetViewModel model = new HouseAddGetViewModel();
            model.Regions = regions;
            model.RoomTypes = roomTypes;
            model.Statuses = statuses;
            model.DecorateStatuses = decorateStatuses;
            model.Attachments = attachments;
            model.Types = types;
            return View(model);
        }


        [HttpPost]
        [ValidateInput(false)]
        [AdminAuthorize(IsCheck = true)]
        public ActionResult Add(HouseAddViewModel model)
        {
            long? userId = AdminHelper.GetUserId(HttpContext);
            long? cityId = userSerivce.GetById(userId.Value).CityId;
            if (cityId == null)
            {
                return Json(new AjaxResult { Status = "error", ErrorMsg = "总部不能进行房源管理" });
            }

            HouseDTO dto = new HouseDTO();
            dto.CommunityId = model.CommunityId;
            dto.RoomTypeId = model.RoomTypeId;
            dto.Address = model.Address;
            dto.MonthRent = model.MonthRent;
            dto.StatusId = model.StatusId;
            dto.Area = model.Area;
            dto.DecorateStatusId = model.DecorateStatusId;
            dto.TotalFloorCount = model.TotalFloorCount;
            dto.FloorIndex = model.FloorIndex;
            dto.TypeId = model.TypeId;
            dto.Direction = model.Direction;
            dto.LookableDateTime = model.LookableDateTime;
            dto.CheckInDateTime = model.CheckInDateTime;
            dto.OwnerName = model.OwnerName;
            dto.OwnerPhoneNum = model.OwnerPhoneNum;
            dto.Description = model.Description;
            dto.AttachmentIds = model.AttachmentIds;

            long houseId = houseService.Add(dto);
            CreateStaticPage(houseId); //生成静态页面           

            //生成房源查看的html文件
            return Json(new AjaxResult { Status = "ok" });
        }
        #endregion

        #region 修改
        [HttpGet]
        [AdminAuthorize(IsCheck = true)]
        public ActionResult Edit(long id)
        {
            long? userId = AdminHelper.GetUserId(HttpContext);
            long? cityId = userSerivce.GetById(userId.Value).CityId;
            if (cityId == null)
            {
                return View("Error", (object)"总部不能进行房源管理");
            }

            HouseDTO house = houseService.GetDTOById(id);
            if (house == null)
            {
                return View("Error", (object)"获取不到房源信息");
            }

            #region 获取区域，并选中
            List<SelectListItem> listRegion = new List<SelectListItem>();
            var regions = regionService.GetByCityId(cityId.Value);
            foreach (var region in regions)
            {
                if (region.Id == house.RegionId)
                {
                    listRegion.Add(new SelectListItem { Value = region.Id.ToString(), Text = region.Name, Selected = true });
                }
                else
                {
                    listRegion.Add(new SelectListItem { Value = region.Id.ToString(), Text = region.Name });
                }
            }
            ViewBag.ListRegion = listRegion;
            #endregion

            #region 获取小区，并选中
            List<SelectListItem> listCommunity = new List<SelectListItem>();
            var communities = communityService.GetByRegionId(house.RegionId);
            foreach (var community in communities)
            {
                if (community.Id == house.CommunityId)
                {
                    listCommunity.Add(new SelectListItem { Value = community.Id.ToString(), Text = community.Name, Selected = true });
                }
                else
                {
                    listCommunity.Add(new SelectListItem { Value = community.Id.ToString(), Text = community.Name });
                }
            }
            ViewBag.ListCommunity = listCommunity;
            #endregion

            var roomTypes = idNameService.GetAll("户型");
            var statuses = idNameService.GetAll("房屋状态");
            var decorateStatuses = idNameService.GetAll("装修状态");
            var attachments = attachmentService.GetAttachments();
            var types = idNameService.GetAll("房屋类别");

            HouseEditGetViewModel model = new HouseEditGetViewModel();
            model.House = house;
            model.RoomTypes = roomTypes;
            model.Statuses = statuses;
            model.DecorateStatuses = decorateStatuses;
            model.Attachments = attachments;
            model.Types = types;
            return View(model);
        }


        [HttpPost]
        [ValidateInput(false)]
        [AdminAuthorize(IsCheck = true)]
        public ActionResult Edit(HouseEditViewModel model)
        {
            long? userId = AdminHelper.GetUserId(HttpContext);
            long? cityId = userSerivce.GetById(userId.Value).CityId;
            if (cityId == null)
            {
                return Json(new AjaxResult { Status = "error", ErrorMsg = "总部不能进行房源管理" });
            }

            HouseDTO dto = houseService.GetDTOById(model.Id);
            if (dto == null)
            {
                return Json(new AjaxResult { Status = "error", ErrorMsg = "获取不到房源信息" });
            }
            dto.CommunityId = model.CommunityId;
            dto.RoomTypeId = model.RoomTypeId;
            dto.Address = model.Address;
            dto.MonthRent = model.MonthRent;
            dto.StatusId = model.StatusId;
            dto.Area = model.Area;
            dto.DecorateStatusId = model.DecorateStatusId;
            dto.TotalFloorCount = model.TotalFloorCount;
            dto.FloorIndex = model.FloorIndex;
            dto.TypeId = model.TypeId;
            dto.Direction = model.Direction;
            dto.LookableDateTime = model.LookableDateTime;
            dto.CheckInDateTime = model.CheckInDateTime;
            dto.OwnerName = model.OwnerName;
            dto.OwnerPhoneNum = model.OwnerPhoneNum;
            dto.Description = model.Description;
            dto.AttachmentIds = model.AttachmentIds;

            houseService.Update(dto);
            CreateStaticPage(model.Id); //生成静态页面           

            //生成房源查看的html文件
            return Json(new AjaxResult { Status = "ok" });
        }
        #endregion

        [HttpPost]
        public ActionResult LoadCommunities(long regionId)
        {
            CommunityDTO[] communities = communityService.GetByRegionId(regionId);
            var data = communities.Select(c => new { id = c.Id, name = c.Name });
            return Json(new AjaxResult { Status = "ok", Data = data });
        }



        #region 删除
        [HttpPost]
        [AdminAuthorize(IsCheck = true)]
        public ActionResult Delete(long id)
        {
            HouseDTO entity = houseService.GetDTOById(id);
            if (entity == null)
            {
                return View("Error", (object)"获取不到房源信息");
            }
            houseService.MarkDeleted(id);
            return Json(new AjaxResult { Status = "ok" });
        }

        [HttpPost]
        [AdminAuthorize(IsCheck = true)]
        public ActionResult BatchDelete(long[] selectdIds)
        {
            List<long> list = new List<long>();
            foreach (long id in selectdIds)
            {
                list.Add(id);
            }
            houseService.BatchMarkDeleted(list);
            return Json(new AjaxResult { Status = "ok" });
        }
        #endregion

        #region 生成静态页


        [HttpPost]
        public ActionResult RebuildAllStaticPage(long cityId, long typeId)
        {
            CityDTO city = cityService.GetDTOById(cityId);
            if (city == null)
            {
                return Json(new AjaxResult { Status = "error", ErrorMsg = "获取不到城市信息" });
            }

            IdNameDTO idName = idNameService.GetDTOById(typeId);
            if (idName == null)
            {
                return Json(new AjaxResult { Status = "error", ErrorMsg = "获取不到房屋类别信息" });
            }

            var houses = houseService.GetHouses(cityId, typeId);
            foreach (var house in houses)
            {
                CreateStaticPage(house.Id);
            }
            return Json(new AjaxResult { Status = "ok" });
        }

        //[HttpGet]
        //public ActionResult RebuildAllStaticPage()
        //{
        //    var houses = houseService.GetHouses();
        //    foreach (var house in houses)
        //    {
        //        CreateStaticPage(house.Id);
        //    }
        //    //return Json(new AjaxResult { Status = "ok" });
        //    return Content("静态页（共有数据 " + houses.Count() + " 条）生成成功");
        //}

        /// <summary>
        /// 生成静态页
        /// </summary>
        /// <param name="houseId"></param>
        private void CreateStaticPage(long houseId)
        {
            var house = houseService.GetDTOById(houseId);
            var pics = housePicService.GetByHouseId(houseId);
            var attachments = attachmentService.GetByHouseId(houseId);
            var goodHouses = houseService.GetHousesByCommunityId((long)house.CommunityId, 3);

            HouseIndexViewModel model = new HouseIndexViewModel();
            model.House = house;
            model.Pics = pics;
            model.Attachments = attachments;
            model.GoodHouses = goodHouses;
            string html = MVCHelper.RenderViewToString(this.ControllerContext, @"~/Areas/WebAdmin/Views/House/StaticIndex.cshtml", model);
            string houseDir = HttpContext.Server.MapPath("~/House/");
            if (!Directory.Exists(houseDir))
            {
                Directory.CreateDirectory(houseDir);
            }
            System.IO.File.WriteAllText(houseDir + houseId + ".html", html);

            //Response.Write("<p>/House/" + houseId + ".html" + " " + house.CommunityName + house.Address + "</p>");
            //Response.Flush();
        }

        [HttpGet]
        public ActionResult RebuildAllStaticPage()
        {
            //缓存key
            ViewBag.Key = Guid.NewGuid().ToString();
            return View();
        }

        [HttpPost]
        public void RebuildAllStaticPageShow(string key)
        {
            //Response.Write("====================== 生成静态页 begin ======================");
            //Response.Flush();
            var houses = houseService.GetHouses();
            //生成页面总数
            int totleCount = houses.Count();
            //已生成页面数量
            int rebuildCount = 0;
            string percent = "";
            //缓存key
            string cacheKey = "StaticPage_" + key;
            foreach (var house in houses)
            {
                //生成静态页
                CreateStaticPage(house.Id);
                //已生成页面数量
                rebuildCount++;
                //计算百分比
                percent = (((rebuildCount * 1.0) / totleCount) * 100).ToString("0") + "%";
                //写入缓存
                HttpContext.Cache.Insert(cacheKey, new RebuildStaticPageResult { TotleCount = totleCount, RebuildCount = rebuildCount, Percent = percent }, null, DateTime.Now.AddMinutes(3), TimeSpan.Zero);
                // Website.Common.MemcacheMgr.Instance.SetValue(cacheKey, new RebuildStaticPageResult { TotleCount = totleCount, RebuildCount = rebuildCount, Percent = percent } , TimeSpan.FromMinutes(3));

            }
            //Response.Write("====================== 生成静态页 end ======================");
            //Response.Flush();
        }

        /// <summary>
        /// 生成进度
        /// </summary>
        /// <param name="key"></param>
        /// <returns></returns>
        [HttpPost]
        public ActionResult GetRebuildStaticPageProgress(string key)
        {
            string cacheKey = "StaticPage_" + key;
            //读取缓存
            RebuildStaticPageResult model = (RebuildStaticPageResult)HttpContext.Cache[cacheKey];
            //RebuildStaticPageResult model = Website.Common.MemcacheMgr.Instance.GetValue<RebuildStaticPageResult>(cacheName);
            if (model == null)
            {
                return Json(new RebuildStaticPageResult { TotleCount = 0, RebuildCount = 0, Percent = "0%" });
            }
            return Json(new RebuildStaticPageResult { TotleCount = model.TotleCount, RebuildCount = model.RebuildCount, Percent = model.Percent });
        }
        #endregion

        #region 房源图片
        public ActionResult PicUpload(int houseId)
        {
            HouseDTO house = houseService.GetDTOById(houseId);
            if (house == null)
            {
                return View("Error", (object)"获取不到房源信息");
            }
            return View(houseId);
        }

        public ActionResult UploadPic(int houseId, HttpPostedFileBase file)
        {
            HouseDTO house = houseService.GetDTOById(houseId);
            if (house == null)
            {
                //return Json(new AjaxResult { Status = "error", ErrorMsg = "获取不到房源信息" });
                throw new Exception("获取不到房源信息");
            }

            //month月，minute
            string md5 = CommonHelper.CalcMD5(file.InputStream);
            string ext = Path.GetExtension(file.FileName);
            string path = "/upload/house/" + DateTime.Now.ToString("yyyy/MM/dd") + "/" + md5 + ext;// /upload/2017/07/07/afadsfa.jpg
            string thumbPath = "/upload/house/" + DateTime.Now.ToString("yyyy/MM/dd") + "/" + md5 + "_thumb" + ext;
            string fullPath = HttpContext.Server.MapPath("~" + path);//d://22/upload/2017/07/07/afadsfa.jpg
            string thumbFullPath = HttpContext.Server.MapPath("~" + thumbPath);
            new FileInfo(fullPath).Directory.Create();//尝试创建可能不存在的文件夹

            file.InputStream.Position = 0;//指针复位
            //file.SaveAs(fullPath);//SaveAs("d:/1.jpg");
            //缩略图
            ImageProcessingJob jobThumb = new ImageProcessingJob();
            jobThumb.Filters.Add(new FixedResizeConstraint(200, 200));//缩略图尺寸200*200
            jobThumb.SaveProcessedImageToFileSystem(file.InputStream, thumbFullPath);

            file.InputStream.Position = 0;//指针复位

            //水印
            ImageWatermark imgWatermark =
                new ImageWatermark(HttpContext.Server.MapPath("~/Areas/WebAdmin/images/logo.png"));
            imgWatermark.ContentAlignment = System.Drawing.ContentAlignment.BottomRight;//水印位置
            imgWatermark.Alpha = 50;//透明度，需要水印图片是背景透明的png图片
            ImageProcessingJob jobNormal = new ImageProcessingJob();
            jobNormal.Filters.Add(imgWatermark);//添加水印
            jobNormal.Filters.Add(new FixedResizeConstraint(600, 600));
            jobNormal.SaveProcessedImageToFileSystem(file.InputStream, fullPath);

            housePicService.Add(new HousePicDTO { HouseId = houseId, Url = path, ThumbUrl = thumbPath });

            CreateStaticPage(houseId);//上传了新图片或者删除图片都要重新生成html页面

            return Json(new AjaxResult
            {
                Status = "ok"
            });
        }

        public ActionResult PicList(long id)
        {
            HouseDTO house = houseService.GetDTOById(id);
            if (house == null)
            {
                return View("Error", (object)"获取不到房源信息");
            }

            var pics = housePicService.GetByHouseId(id);
            return View(pics);
        }

        public ActionResult DeletePics(long[] selectedIds)
        {

            List<long> list = new List<long>();
            foreach (var id in selectedIds)
            {
                list.Add(id);
            }
            housePicService.BatchMarkDeleted(list);

            //CreateStaticPage(houseId);//上传了新图片或者删除图片都要重新生成html页面
            //不建议删除图片
            return Json(new AjaxResult { Status = "ok" });
        }
        #endregion
    }

    [Serializable]
    public class RebuildStaticPageResult
    {
        /// <summary>
        /// 生成页面总数
        /// </summary>
        public int TotleCount { get; set; }
        /// <summary>
        /// 已生成页面数量
        /// </summary>
        public int RebuildCount { get; set; }
        /// <summary>
        /// 生成页面数量百分比
        /// </summary>
        public string Percent { get; set; }
    }
}